package com.wu.aop;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.wu.exception.BusinessException;
import com.wu.exception.EnumInterface;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
public class WebLogAspect {
    private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";
    private static final Logger log = LoggerFactory.getLogger(WebLogAspect.class);

    //设置切点 匹配规则
    @Pointcut("@annotation(com.wu.aop.LogRecord)")
    public void webLog() {

    }

    @Around("webLog()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        StringBuffer classAndMethod = new StringBuffer();
        LogRecord methodAnnotation = method.getAnnotation(LogRecord.class);
        if (methodAnnotation != null) {
            classAndMethod.append(methodAnnotation.value());
        }

        String params = null;
        params = JSONObject.toJSONStringWithDateFormat(joinPoint.getArgs(), dateFormat, SerializerFeature.WriteMapNullValue);
        if(methodAnnotation.request()){
            // 接收到请求，记录请求内容
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            // 记录下请求内容
            log.info("url:{},ip:{},request:{}",request.getRequestURL().toString(),request.getRemoteAddr(),params);
            //保存请求数据
            if(methodAnnotation.save()){
                //TODO
            }
        }

        long start = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        if(methodAnnotation.response()){
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            log.info("url:{},ip:{},response:{}",request.getRequestURL().toString(),request.getRemoteAddr(),JSONObject.toJSONStringWithDateFormat(result, dateFormat, SerializerFeature.WriteMapNullValue));
        }
        return result;
    }

    @AfterThrowing(throwing = "e", pointcut = "webLog()")
    public void throwing(JoinPoint joinPoint, Exception e) {
        if(e instanceof BusinessException){
            BusinessException businessException = (BusinessException) e;
            EnumInterface errorCode = businessException.getErrorCode();
            if(errorCode != null){
                log.error("webLog error,code:{},msg:{}",errorCode.getCode(),errorCode.getMsg());

            }
        }else {
            log.error("webLog error:"+ e.getMessage());
        }
    }
}